package cn.hxzy.controller;
import cn.hxzy.common.Result;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;

import net.minidev.json.JSONObject;
import org.codehaus.jettison.json.JSONException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {

    @Resource
    OSS ossClient;

    @Value("${bucketName}")
    private String bucketName;

    @Value("${oss-img-path}")
    private String ossImgPath;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessKey;
    @Value("${spring.cloud.alicloud.secret-key}")
    private String secretkey;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;




    @PostMapping("/imgUpload")
    public Result up(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
        OSSClient ossClient = new OSSClient(endpoint, accessKey, secretkey);
        InputStream inputStream = file.getInputStream();
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 最后上传生成的文件名
        String finalFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffixName;
        try {
            ossClient.putObject(bucketName, finalFileName, inputStream);
            ossClient.shutdown();
            System.out.println(finalFileName);
            System.out.println(ossImgPath + finalFileName);
            return Result.ok().data("uploadImg",ossImgPath + finalFileName);
        } catch (Exception e) {
            return Result.error().message("上传失败");
        }
    }


    @GetMapping("/getPolicy")
    public JSONObject getPolicy() throws UnsupportedEncodingException, JSONException {
        // host的格式为 bucketname.endpoint
        StringBuilder builder = new StringBuilder();
        String host = "https://"+ bucketName+ "."+endpoint;

        // callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
        // String callbackUrl = "http://88.88.88.88:8888";
        // 每一天产生一个文件夹
        String dir = LocalDate.now().toString() + "/"; // 用户上传文件时指定的前缀,如果是 / 则自动检测为文件夹。

        JSONObject jsonObject = new JSONObject();

        long expireTime = 100;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000; //过期时间 100 秒
        Date expiration = new Date(expireEndTime);
        // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
        String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
        byte[] binaryData = postPolicy.getBytes("utf-8");
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = ossClient.calculatePostSignature(postPolicy);

        jsonObject.put("OSSAccessKeyId", accessKey);
        jsonObject.put("policy", encodedPolicy);
        jsonObject.put("signature", postSignature);
        jsonObject.put("dir", dir);
        jsonObject.put("host", host);
        jsonObject.put("expire", String.valueOf(expireEndTime / 1000));
        return jsonObject;
    }

}
